import React, { useState } from 'react';
import { AlertCircle, Search } from 'lucide-react';
import { TextInput } from '../components/shared/ModelOptions';

const FinanceVectorPage = () => {
  const [query, setQuery] = useState('');
  const [result, setResult] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [limit, setLimit] = useState(10);
  const [searchHistory, setSearchHistory] = useState([]);
  
  const handleSubmit = async () => {
    if (!query.trim()) return;
    
    setIsLoading(true);
    try {
      const response = await fetch('http://10.128.4.197:8000/api/finance-vector', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          query: query,
          options: {
            limit: parseInt(limit)
          }
        }),
      });
      
      const data = await response.json();
      setResult(data);
      
      // 添加到搜索历史
      if (!searchHistory.includes(query)) {
        setSearchHistory(prev => [query, ...prev].slice(0, 5));
      }
    } catch (error) {
      console.error('Error:', error);
      setResult({ 
        query: query, 
        results: [], 
        error: '请求处理失败：' + (error.message || '未知错误')
      });
    }
    setIsLoading(false);
  };
  
  // 执行推荐查询
  const handleRecommendedQuery = (recommendedQuery) => {
    setQuery(recommendedQuery);
    setTimeout(() => {
      handleSubmit();
    }, 100);
  };
  
  // 执行搜索历史中的查询
  const handleHistoryQuery = (historyQuery) => {
    setQuery(historyQuery);
    setTimeout(() => {
      handleSubmit();
    }, 100);
  };
  
  // 计算相似度条宽度
  const getSimilarityBarWidth = (similarity) => {
    return Math.round(similarity * 100) + '%';
  };
  
  // 常用推荐查询
  const recommendedQueries = [
    "投资理财",
    "基金",
    "股票",
    "债券",
    "风险管理",
    "信用卡",
    "银行服务",
    "保险产品",
    "ETF",
    "资产配置"
  ];

  return (
    <div className="max-w-4xl mx-auto">
      <h1 className="text-3xl font-bold mb-6">金融术语搜索 📊</h1>
      
      <div className="bg-white shadow-md rounded-lg p-6 mb-6">
        <h2 className="text-xl font-semibold mb-4">搜索金融术语</h2>
        
        <div className="mb-4">
          <div className="flex items-center">
            <div className="flex-1">
              <TextInput
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                rows={2}
                placeholder="请输入金融术语或关键词，例如：基金、股票、风险管理..."
                onKeyDown={(e) => {
                  if (e.key === 'Enter' && !e.shiftKey) {
                    e.preventDefault();
                    handleSubmit();
                  }
                }}
              />
            </div>
            <button
              onClick={handleSubmit}
              disabled={isLoading}
              className={`ml-3 bg-blue-500 text-white p-3 rounded-md hover:bg-blue-600 h-12 w-12 flex items-center justify-center ${
                isLoading ? 'opacity-50 cursor-not-allowed' : ''
              }`}
            >
              <Search size={20} />
            </button>
          </div>
        </div>
        
        {/* 推荐查询 */}
        <div className="mb-4">
          <h3 className="text-sm font-medium text-gray-700 mb-2">推荐搜索：</h3>
          <div className="flex flex-wrap gap-2">
            {recommendedQueries.map((q, idx) => (
              <button 
                key={idx} 
                onClick={() => handleRecommendedQuery(q)}
                className="bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm px-3 py-1 rounded-full"
              >
                {q}
              </button>
            ))}
          </div>
        </div>
        
        {/* 搜索历史 */}
        {searchHistory.length > 0 && (
          <div className="mb-4">
            <h3 className="text-sm font-medium text-gray-700 mb-2">搜索历史：</h3>
            <div className="flex flex-wrap gap-2">
              {searchHistory.map((q, idx) => (
                <button 
                  key={idx} 
                  onClick={() => handleHistoryQuery(q)}
                  className="bg-blue-50 hover:bg-blue-100 text-blue-700 text-sm px-3 py-1 rounded-full flex items-center"
                >
                  <Search size={12} className="mr-1" /> {q}
                </button>
              ))}
            </div>
          </div>
        )}
        
        <div className="mt-4">
          <label className="block text-sm font-medium text-gray-700 mb-1">
            结果数量
          </label>
          <input
            type="number"
            className="w-24 border rounded-md px-3 py-2"
            value={limit}
            min={1}
            max={50}
            onChange={(e) => setLimit(e.target.value)}
          />
        </div>
      </div>
      
      {result && (
        <div className="bg-white shadow-md rounded-lg p-6 mb-6">
          <h2 className="text-xl font-semibold mb-4">搜索结果</h2>
          
          {result.error ? (
            <div className="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 mb-4">
              <p className="font-bold">错误：</p>
              <p>{result.error}</p>
            </div>
          ) : result.results && result.results.length > 0 ? (
            <>
              <p className="mb-3">找到 {result.results.length} 条相关结果：</p>
              
              {/* 结果列表 */}
              <div className="space-y-4">
                {result.results.map((item, index) => {
                  const similarity = item.similarity;
                  const similarityPercentage = Math.round(similarity * 100);
                  // 决定相似度显示颜色
                  let similarityColor = "bg-red-500";
                  if (similarity > 0.7) similarityColor = "bg-green-500";
                  else if (similarity > 0.5) similarityColor = "bg-yellow-500";
                  
                  return (
                    <div key={index} className="border rounded-lg p-4 hover:bg-gray-50">
                      {/* 相似度条 */}
                      <div className="mb-2 flex items-center">
                        <div className="text-sm font-medium mr-2">相似度:</div>
                        <div className="flex-1 bg-gray-200 rounded-full h-2.5">
                          <div 
                            className={`h-2.5 rounded-full ${similarityColor}`} 
                            style={{width: getSimilarityBarWidth(similarity)}}
                          ></div>
                        </div>
                        <div className="ml-2 text-sm font-medium">{similarityPercentage}%</div>
                      </div>
                      
                      {/* 结果内容 */}
                      <div>
                        {/* 优先显示术语和描述字段 */}
                        {item.term && (
                          <div className="text-lg font-semibold mb-2">{item.term}</div>
                        )}
                        
                        {item.description && (
                          <div className="mb-3">
                            <p>{item.description}</p>
                          </div>
                        )}
                        
                        {/* 显示风险等级，用不同颜色区分 */}
                        {item.risk_level && (
                          <div className="mb-3">
                            <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                              item.risk_level.includes('高') ? 'bg-red-100 text-red-800' : 
                              item.risk_level.includes('中') ? 'bg-yellow-100 text-yellow-800' : 
                              'bg-green-100 text-green-800'
                            }`}>
                              {item.risk_level}
                            </span>
                            {item.category && (
                              <span className="inline-flex items-center ml-2 px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                {item.category}
                              </span>
                            )}
                          </div>
                        )}
                        
                        {/* 显示投资建议 */}
                        {item.tips && (
                          <div className="bg-blue-50 border-l-4 border-blue-400 p-3 mb-3">
                            <div className="flex">
                              <div className="flex-shrink-0">
                                <svg className="h-5 w-5 text-blue-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                                  <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z" clipRule="evenodd" />
                                </svg>
                              </div>
                              <div className="ml-3">
                                <p className="text-sm text-blue-700">{item.tips}</p>
                              </div>
                            </div>
                          </div>
                        )}
                        
                        {/* 显示其他字段，排除已显示的基础字段和similarity */}
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-2 mt-2">
                          {Object.entries(item)
                            .filter(([key]) => !['similarity', 'term', 'description', 'risk_level', 'category', 'tips'].includes(key))
                            .map(([key, value], idx) => (
                              <div key={idx} className="bg-gray-50 px-3 py-1 rounded">
                                <span className="font-medium text-gray-700 capitalize">{key.replace(/_/g, ' ')}: </span>
                                <span>{value}</span>
                              </div>
                            ))}
                        </div>
                        
                        {/* 如果没有任何内容字段，显示提示 */}
                        {Object.keys(item).filter(key => key !== 'similarity').length === 0 && (
                          <div className="italic text-gray-500">
                            未找到详细内容描述
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </>
          ) : (
            <div className="text-center py-8">
              <div className="text-gray-400 mb-2">
                <Search size={48} className="mx-auto" />
              </div>
              <p>未找到相关结果</p>
              <p className="text-sm text-gray-500 mt-2">尝试使用不同的关键词或更广泛的搜索术语</p>
            </div>
          )}
        </div>
      )}
      
      <div className="flex items-center text-yellow-700 bg-yellow-100 p-4 rounded-md">
        <AlertCircle className="mr-2" />
        <span>金融术语搜索基于向量数据库，可以找到与查询内容语义相关的金融术语及其解释。结果包括术语描述、风险等级和相关建议。</span>
      </div>
    </div>
  );
};

export default FinanceVectorPage; 